package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.response.ArrivalRate;
import com.xmy.cultivate.entity.views.RenewClassRecord;
import com.xmy.cultivate.entity.views.ShiftList;
import com.xmy.cultivate.enums.StatusGradeEnum;
import com.xmy.cultivate.exception.CommonException;
import com.xmy.cultivate.mapper.*;
import com.xmy.cultivate.respons.NotScheduled;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.CommonUtil;
import com.xmy.cultivate.util.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 学生所在班级与课程 服务实现类
 * </p>
 *
 * @author min
 * @since 2022-08-09
 */
@Service
public class StudentGradeServiceImpl extends ServiceImpl<StudentGradeMapper, StudentGrade> implements IStudentGradeService {

    @Autowired
    @Lazy
    StudentGradeMapper studentGradeMapper;

    @Autowired
    @Lazy
    OrderDetailMapper orderDetailMapper;

    @Autowired
    @Lazy
    GradeMapper gradeMapper;

    @Autowired
    @Lazy
    CourseMapper courseMapper;

    @Autowired
    @Lazy
    IRenewDataService iRenewDataService;

    @Autowired
    @Lazy
    CourseSchedulingAlwaysMapper courseSchedulingAlwaysMapper;

    @Autowired
    IQuarterService iQuarterService;

    @Autowired
    ITrackMarketService iTrackMarketService;

    @Autowired
    TrackMarketMapper trackMarketMapper;

    @Autowired
    ISchoolQuarterService iSchoolQuarterService;

    public IPage<ShiftList> findAll(IPage<?> page, Wrapper wrapper) {
        return studentGradeMapper.findAll(page, wrapper);
    }

    public boolean divideClasses(Long orderDetailId, Long gradeId) {

        OrderDetail orderDetail = orderDetailMapper.selectById(orderDetailId);
        if (orderDetail == null) {
            throw new CommonException(ResultCode.ORDERDETAIL_NOT);
        } else if (orderDetail.getResidueCourseCount() <= 0) {
            throw new CommonException(ResultCode.NOR_COURSE);
        }

        Grade grade = gradeMapper.selectById(gradeId);
        if (grade == null) {
            throw new CommonException(ResultCode.GRADE_NOT);
        } else if (grade.getStatus() != StatusGradeEnum.NORMAL) {
            throw new CommonException(ResultCode.KNOTGRADE);
        }

        StudentGrade studentGrade = new StudentGrade();
        studentGrade.setOrderDetailId(orderDetail.getId());
        studentGrade.setStudentId(orderDetail.getStudentId());
        studentGrade.setSchoolId(orderDetail.getSchoolId());
        studentGrade.setGradeId(grade.getId());
        studentGrade.setCourseId(orderDetail.getCourseId());
        studentGrade.setSubjectsId(orderDetail.getSubjectsId());
        studentGrade.setEndDate(grade.getEndDate());

        //studentGrade.setUseCourseCount();
        /*Long renewTeacherId = grade.getTeacherId();
        Integer isRenew = 1;
        //课次
        if((orderDetail.getResidueCourseCount()/orderDetail.getCourseHouse())<3){
            isRenew = 0;
            //应续班老师,为原来的带班老师，待设定
        }else {
            //应续班老师
            studentGrade.setRenewTeacherId(renewTeacherId);
        }*/

        studentGrade.setYearPart(orderDetail.getYearPart());
        studentGrade.setQuarterNum(orderDetail.getQuarterNum());
        studentGrade.setSurplusCourseNum(orderDetail.getResidueCourseCount());
        //studentGrade.setIsRenew(isRenew);
        Integer rs = studentGradeMapper.insert(studentGrade);
        Course course = courseMapper.selectById(grade.getCourseId());

        //更新续班里的老师
        iRenewDataService.updateTeacher(grade.getSchoolId(), orderDetail.getStudentId(), course, grade);


        return rs > 0 ? true : false;
        //return  studentGradeMapper.divideClasses(Long orderDetailId,Long gradeId);
    }

    /**
     * 调班
     *
     * @param paramStudentGrade
     * @return
     */
    @Transactional
    public boolean melodyClass(StudentGrade paramStudentGrade) {
        return true;
    }


    public boolean addData(Long orderDetailId, Long schoolId, Long studentId, Long gradeId, Long courseId, Long subjectsId, Integer yearPart, Integer quarterNum, Integer surplusCourseNum) {
        StudentGrade studentGrade = new StudentGrade();
        studentGrade.setOrderDetailId(orderDetailId);
        studentGrade.setSchoolId(schoolId);
        studentGrade.setStudentId(studentId);
        studentGrade.setGradeId(gradeId);
        studentGrade.setCourseId(courseId);
        studentGrade.setSubjectsId(subjectsId);
        studentGrade.setYearPart(yearPart);
        studentGrade.setQuarterNum(quarterNum);
        studentGrade.setSurplusCourseNum(surplusCourseNum);
        studentGradeMapper.insert(studentGrade);
        return true;
    }

    /**
     * 获取最后一次后班数据
     *
     * @param schoolId
     * @param studentId
     * @param subjectsId
     * @param yearPart
     * @param quaterNum
     * @return
     */
    @Override
    public StudentGrade getLastStudentGradeForOrderDetailId(Long schoolId, Long studentId, Long subjectsId, Integer yearPart, Integer quaterNum, boolean isInludeSchool, Integer lessonType) {
        StudentGrade studentGrade = this.getStudentGradeForOrderDetailIdOne(schoolId, studentId, subjectsId, yearPart, quaterNum, 1, isInludeSchool, lessonType);
        if (studentGrade == null) {
            studentGrade = this.getStudentGradeForOrderDetailIdOne(schoolId, studentId, subjectsId, yearPart, quaterNum, 5, isInludeSchool, lessonType);
        }
        if (studentGrade == null) {
            studentGrade = this.getStudentGradeForOrderDetailIdOne(schoolId, studentId, subjectsId, yearPart, quaterNum, 6, isInludeSchool, lessonType);
        }
        if (studentGrade == null) {
            studentGrade = this.getStudentGradeForOrderDetailIdOne(schoolId, studentId, subjectsId, yearPart, quaterNum, 4, isInludeSchool, lessonType);
        }
        if (studentGrade == null) {
            studentGrade = this.getStudentGradeForOrderDetailIdOne(schoolId, studentId, subjectsId, yearPart, quaterNum, 3, isInludeSchool, lessonType);
        }
        return studentGrade;
    }

    public StudentGrade getStudentGradeForOrderDetailIdOne(Long schoolId, Long studentId, Long subjectsId, Integer yearPart, Integer quaterNum, Integer readingStatus, boolean isInludeSchool, Integer lessonType) {
        QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
        studentGradeQueryWrapper.eq("year_part", yearPart);
        studentGradeQueryWrapper.eq("quarter_num", quaterNum);
        studentGradeQueryWrapper.eq("subjects_id", subjectsId);
        studentGradeQueryWrapper.eq(isInludeSchool, "school_id", schoolId);
        studentGradeQueryWrapper.eq("student_id", studentId);
        studentGradeQueryWrapper.eq("reading_status", readingStatus);
        studentGradeQueryWrapper.eq("lesson_type", lessonType);
        //studentGradeQueryWrapper.eq("reading_status",1);
        studentGradeQueryWrapper.last("limit 1");
        studentGradeQueryWrapper.orderByDesc("id", "created_at");
        StudentGrade studentGrade = this.getOne(studentGradeQueryWrapper);
        return studentGrade;
    }

    /**
     * 在读学员数量
     *
     * @param reMap
     * @return
     */
    @Override
    public Integer inReadStudentCount(Map reMap) {
        String schoolId = (String) reMap.get("schoolId");
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String subjectsId = (String) reMap.get("subjectsId");

        Integer inReadStudentCount = studentGradeMapper.readingStudentCount(yearPart, quarterNum, schoolId, subjectsId);
        return inReadStudentCount;
    }

    /**
     * 异常学员数量
     *
     * @param reMap
     * @return
     */
    @Override
    public Integer abnormalStudentCount(Map reMap) {
        String schoolId = (String) reMap.get("schoolId");
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String subjectsId = (String) reMap.get("subjectsId");

        Integer errorStudentCount = studentGradeMapper.abnormalStudentCount(yearPart, quarterNum, schoolId, subjectsId);
        return errorStudentCount;
    }

    /**
     * 结课学员数量
     *
     * @param reMap
     * @return
     */
    @Override
    public Integer overStudentCount(Map reMap) {
        String schoolId = (String) reMap.get("schoolId");
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String subjectsId = (String) reMap.get("subjectsId");
        Integer overStudentCount = studentGradeMapper.countStudentByStatusJoint(yearPart, quarterNum, schoolId, subjectsId);
        return overStudentCount;
    }

    /**
     * 退费学员数量
     *
     * @param reMap
     * @return
     */
    @Override
    public Integer returnStudentCount(Map reMap) {
        String schoolId = (String) reMap.get("schoolId");
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String subjectsId = (String) reMap.get("subjectsId");

        Integer returnStudentCount = studentGradeMapper.returnStudentCount(yearPart, quarterNum, schoolId, subjectsId);

        return returnStudentCount;
    }

    /**
     * 转校学员数量
     *
     * @param reMap
     * @return
     */
    @Override
    public Integer changeStudentCount(Map reMap) {
        String schoolId = (String) reMap.get("schoolId");
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String subjectsId = (String) reMap.get("subjectsId");

        Integer changeStudentCount = studentGradeMapper.turnOutStudentCount(yearPart, quarterNum, schoolId, subjectsId);
        return changeStudentCount;
    }

    /**
     * 停课学员数量
     *
     * @param reMap
     * @return
     */
    @Override
    public Integer stopStudentCount(Map reMap) {
        String schoolId = (String) reMap.get("schoolId");
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String subjectsId = (String) reMap.get("subjectsId");

        Integer stopStudentCount = studentGradeMapper.stopStudnetCount(yearPart, quarterNum, schoolId, subjectsId);
        return stopStudentCount;
    }

    //=============================================================


    /**
     * 在读学员数量
     *
     * @param reMap
     * @return
     */
    public List<StudentGrade> inReadStudentList(Map reMap) {
        String schoolId = (String) reMap.get("schoolId");
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String subjectsId = (String) reMap.get("subjectsId");

        List<StudentGrade> inReadStudentCount = studentGradeMapper.readingStudentList(yearPart, quarterNum, schoolId, subjectsId);
        return inReadStudentCount;
    }

    /**
     * 异常学员数量
     *
     * @param reMap
     * @return
     */
    public List<StudentGrade> abnormalStudentList(Map reMap) {
        String schoolId = (String) reMap.get("schoolId");
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String subjectsId = (String) reMap.get("subjectsId");

        List<StudentGrade> errorStudentCount = studentGradeMapper.abnormalStudentList(yearPart, quarterNum, schoolId, subjectsId);
        return errorStudentCount;
    }

    /**
     * 结课学员数量
     *
     * @param reMap
     * @return
     */
    public List<StudentGrade> overStudentList(Map reMap) {
        String schoolId = (String) reMap.get("schoolId");
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String subjectsId = (String) reMap.get("subjectsId");
        List<StudentGrade> overStudentCount = studentGradeMapper.countStudentByStatusList(yearPart, quarterNum, schoolId, subjectsId);
        return overStudentCount;
    }

    /**
     * 退费学员数量
     *
     * @param reMap
     * @return
     */
    public List<StudentGrade> returnStudentList(Map reMap) {
        String schoolId = (String) reMap.get("schoolId");
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String subjectsId = (String) reMap.get("subjectsId");

        List<StudentGrade> returnStudentCount = studentGradeMapper.returnStudentList(yearPart, quarterNum, schoolId, subjectsId);

        return returnStudentCount;
    }

    /**
     * 转校学员数量
     *
     * @param reMap
     * @return
     */
    public List<StudentGrade> changeStudentList(Map reMap) {
        String schoolId = (String) reMap.get("schoolId");
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String subjectsId = (String) reMap.get("subjectsId");

        List<StudentGrade> changeStudentCount = studentGradeMapper.turnOutStudentList(yearPart, quarterNum, schoolId, subjectsId);
        return changeStudentCount;
    }

    /**
     * 停课学员数量
     *
     * @param reMap
     * @return
     */
    public List<StudentGrade> stopStudentList(Map reMap) {
        String schoolId = (String) reMap.get("schoolId");
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String subjectsId = (String) reMap.get("subjectsId");

        List<StudentGrade> stopStudentCount = studentGradeMapper.stopStudnetList(yearPart, quarterNum, schoolId, subjectsId);
        return stopStudentCount;
    }

    @Override
    public List<StudentGrade> getTaskList(String lessonNum) {
        return studentGradeMapper.getTaskList(lessonNum);
    }

//    @Override
//    public IPage<StudentGrade> getTaskList(IPage<?> page, String lessonNum, String field, String yearClassId, String quarterNum, String courseTypeId, Wrapper wrapper) {
//        return studentGradeMapper.getTaskList(page,lessonNum);
//    }

    public void updateIsPresort(Long schoolId, Long studentId, Integer yearPart, Integer quarterNum, Long subjectsId, Integer lessonType) {
        Integer yearPartAndQuarter = Integer.parseInt(yearPart + "" + quarterNum);
        Integer residueCount = orderDetailMapper.getResidueCourseCount(schoolId, studentId, subjectsId, yearPartAndQuarter, lessonType);
        Quarter nextQuarter = CommonUtil.getNextQuarter(yearPart, quarterNum);

        Integer nextYearPart = nextQuarter.getYearPart();
        Integer nextQuarterNum = nextQuarter.getNum();

        //为了获取年级信息
        OrderDetail lastOrderDetail = orderDetailMapper.getLastOneForStudent(yearPart, quarterNum, studentId, subjectsId, lessonType);

        Integer gradeSection = CommonUtil.getGradeSection(lastOrderDetail.getYearClassId());
        CourseSchedulingAlways courseSchedulingAlways = courseSchedulingAlwaysMapper.getOneForDate(LocalDate.now(), gradeSection);
        if (courseSchedulingAlways != null) {
            if (courseSchedulingAlways.getNum() <= 3) {
                nextYearPart = yearPart;
                nextQuarterNum = quarterNum;
            }

            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
            studentGradeQueryWrapper.eq("year_part", nextYearPart);
            studentGradeQueryWrapper.eq("quarter_num", nextQuarterNum);
            studentGradeQueryWrapper.eq("subjects_id", subjectsId);
            studentGradeQueryWrapper.eq("student_id", studentId);
            if (residueCount < 3) {
                studentGradeQueryWrapper.eq("is_presort", 1);
                List<StudentGrade> studentGradeList = this.list(studentGradeQueryWrapper);
                for (StudentGrade studentGrade : studentGradeList) {
                    studentGrade.setIsPresort(2);
                    studentGrade.setRemark("课时小于等于3，" + "时间：" + LocalDateTime.now().withNano(0));
                    this.updateById(studentGrade);
                }
            } else {
                studentGradeQueryWrapper.ne("is_presort", 1);
                List<StudentGrade> studentGradeList = this.list(studentGradeQueryWrapper);
                for (StudentGrade studentGrade : studentGradeList) {
                    studentGrade.setIsPresort(1);
                    studentGrade.setRemark("课时大于3，" + "时间：" + LocalDateTime.now().withNano(0));
                    this.updateById(studentGrade);
                }
            }
        }
    }

    @Override
    public IPage<StudentGrade> notAlreadyStudent(IPage<?> page, String yearPart, String quarterNum, String subjectsId, String schoolId, String yearClassId, Integer isHistory, String startResidue, String endResidue, String yearAndQuarter) {
        return studentGradeMapper.notAlreadyStudent(page, yearPart, quarterNum, subjectsId, schoolId, yearClassId, isHistory, startResidue, endResidue, yearAndQuarter);
    }

    @Override
    public IPage<StudentGrade> notAlreadyPracticeStudent(IPage<?> page, String yearPart, String quarterNum, String subjectsId, String teacherId, String schoolId, String lessonType, String yearClassId) {
        return studentGradeMapper.notAlreadyPracticeStudent(page, yearPart, quarterNum, subjectsId, teacherId, Integer.valueOf(lessonType), schoolId, yearClassId);
    }

    @Override
    public IPage<StudentGrade> notAlreadyBrushStudentDetail(IPage<?> page, String yearPart, String quarterNum, String subjectsId, String teacherId, String schoolId, String lessonType, String yearClassId) {
        return studentGradeMapper.notAlreadyBrushStudentDetail(page, yearPart, quarterNum, subjectsId, teacherId, Integer.valueOf(lessonType), schoolId, yearClassId);
    }


    @Override
    public IPage<StudentGrade> notAlreadyPracticeCount(IPage<?> page, String yearPart, String quarterNum, String subjectsId, String schoolId, String lessonType, String type, String yearClassId) {
        return studentGradeMapper.notAlreadyPracticeCount(page, yearPart, quarterNum, subjectsId, schoolId, Integer.valueOf(lessonType), Integer.valueOf(type), yearClassId);
    }

    @Override
    public List<StudentGrade> reBrushStudentCount(String yearPart, String quarterNum, String subjectsId, String schoolId, String lessonType, String type, String yearClassId) {
        return studentGradeMapper.reBrushStudentCount(yearPart, quarterNum, subjectsId, schoolId, Integer.valueOf(lessonType), Integer.valueOf(type), yearClassId);
    }

    //调用callStoreAgainBrushData
    public void callStoreAgainBrushData(String yearPart, String quarterNum, String subjectsId, String yearClassId) {
        studentGradeMapper.callStoreAgainBrushData(yearPart, quarterNum, subjectsId, yearClassId);
    }


    @Override
    public Integer alreadyCount(String yearPart, String quarterNum, String subjectsId, Integer isHistory, Long schoolId, String yearClassId, String startResidue, String endResidue) {
        return studentGradeMapper.alreadyCount(yearPart, quarterNum, subjectsId, isHistory, schoolId, yearClassId, startResidue, endResidue);
    }

    @Override
    public Integer notAlreadyCount(String yearPart, String quarterNum, String subjectsId, Long schoolId, String yearClassId, Integer isHistory, String startResidue, String endResidue) {
        return studentGradeMapper.notAlreadyCount(yearPart, quarterNum, subjectsId, schoolId, yearClassId, isHistory, startResidue, endResidue);
    }

    @Override
    public List<StudentGrade> orderDetailList(String yearPart, String quarterNum, String subjectsId, String yearClassId) {
        return studentGradeMapper.orderDetailList(yearPart, quarterNum, subjectsId, yearClassId);
    }

    @Override
    public Long getStudentUseCourseCountAllSchool(Integer yearPart,
                                                  Integer quarterNum,
                                                  Long subjectsId,
                                                  Long studentId,
                                                  Integer lessonType) {
        return studentGradeMapper.getStudentUseCourseCountAllSchool(yearPart, quarterNum, subjectsId, studentId, lessonType);
    }

    @Override
    public List<Grade> getGradeFloatList(String yearPart, String quarterNum, String yearClassId, String classTypeId, String subjectsId, String schoolId, String type, String date) {
        return studentGradeMapper.getGradeFloatList(yearPart, quarterNum, yearClassId, classTypeId, subjectsId, schoolId, type, date);
    }

    @Override
    public IPage<Grade> getGradeFloatDetails(IPage<?> page, String yearPart, String quarterNum, String yearClassId, String classTypeId, String subjectsId, String schoolId, String gradeId, String teacherId, String date) {
        return studentGradeMapper.getGradeFloatDetails(page, yearPart, quarterNum, yearClassId, classTypeId, subjectsId, schoolId, gradeId, teacherId, date);
    }

    @Override
    public IPage<StudentGrade> alreadyStudent(IPage<?> page, String yearPart, String quarterNum, String subjectsId, String schoolId, String yearClassId, String isHistory, String startResidue, String endResidue) {
        return studentGradeMapper.alreadyStudent(page, yearPart, quarterNum, subjectsId, schoolId, yearClassId, isHistory, startResidue, endResidue);
    }

    @Override
    public IPage<StudentGrade> alreadyAllStudent(IPage<?> page, String yearPart, String quarterNum, String subjectsId, String schoolId, String yearClassId, String isHistory, String startResidue, String endResidue) {
        return studentGradeMapper.alreadyAllStudent(page, yearPart, quarterNum, subjectsId, schoolId, yearClassId, isHistory, startResidue, endResidue);
    }

    @Override
    public List<Grade> getGradeFloatTeamList(String yearPart, String quarterNum, String yearClassId, String classTypeId, String subjectsId, String schoolId, String isDetails, String date, String teamId) {
        StringBuilder ids = new StringBuilder();
        TrackMarket market = trackMarketMapper.selectById(teamId);
        if (Objects.nonNull(teamId) && Objects.nonNull(market)) {
            ids.append(teamId);
            if (market.getPid().equals(0) || market.getPid() == 0L) {
                String idByPid = trackMarketMapper.getIdByPid(market.getId(), yearPart, quarterNum, 18);
                if (StringUtils.isNotBlank(idByPid)) {
                    ids.append(",");
                    ids.append(idByPid);
                }
            }
        }
        List<Grade> renewClassRecordList = studentGradeMapper.getGradeFloatTeamList(yearPart, quarterNum, yearClassId, classTypeId, subjectsId, schoolId, isDetails, date, ids.toString());

        // 获取父类战队
        List<Grade> gradeArrayList = new ArrayList<>();
        List<Long> marketIds = new ArrayList<>();
        List<Long> pidList = new ArrayList<>();
        for (Grade renewClassRecord : renewClassRecordList) {
            marketIds.add(renewClassRecord.getTeamPid());
            TrackMarket trackMarket = iTrackMarketService.getById(renewClassRecord.getTeamPid());
            if (trackMarket == null) {
                continue;
            }
            if (!pidList.contains(renewClassRecord.getTeamPid())) {
                Grade grade = new Grade();
                grade.setTeacherName(trackMarket.getTeamName());
                grade.setTeamId(trackMarket.getId());
                grade.setTeamPid(trackMarket.getPid());
                grade.setYearPart(renewClassRecord.getYearPart());
                grade.setQuarterNum(renewClassRecord.getQuarterNum());
                gradeArrayList.add(grade);
            }
            pidList.add(renewClassRecord.getTeamPid());
        }
        //已经存在就不添加
        for (Grade renewClassRecord : gradeArrayList) {
            if (marketIds.contains(renewClassRecord.getTeamId())) {
                renewClassRecordList.add(renewClassRecord);
            }
        }


        //获取父节点
        List<Grade> collect = renewClassRecordList.stream().filter(m -> m.getTeamPid() == 0).map(
                (m) -> {
                    m.setChildren(getChildrens(m, renewClassRecordList));
                    return m;
                }
        ).collect(Collectors.toList());

        return collect;
    }

    @Override
    public IPage<Grade> getGradeFloatTeamDetailsList(IPage<?> page, String yearPart, String quarterNum, String yearClassId, String classTypeId, String subjectsId, String schoolId, String date, String teamId, String teacherId, String gradeId) {
        StringBuilder ids = new StringBuilder();
        TrackMarket trackMarket = trackMarketMapper.selectById(teamId);
        if (Objects.nonNull(teamId) && Objects.nonNull(trackMarket)) {
            ids.append(teamId);
            if (trackMarket.getPid().equals(0) || trackMarket.getPid() == 0L) {
                String idByPid = trackMarketMapper.getIdByPid(trackMarket.getId(), yearPart, quarterNum, 18);
                if (StringUtils.isNotBlank(idByPid)) {
                    ids.append(",");
                    ids.append(idByPid);
                }
            }
        }

        return studentGradeMapper.getGradeFloatTeamDetailsList(page, yearPart, quarterNum, yearClassId, classTypeId, subjectsId, schoolId, date, ids.toString(), teacherId, gradeId);
    }

    @Override
    public List<NotScheduled> alreadyCountNew(String yearPart, String quarterNum, String subjectsId, Integer isHistory, String yearClassId, String startResidue, String endResidue) {
        return studentGradeMapper.alreadyCountNew(yearPart, quarterNum, subjectsId, isHistory, yearClassId, startResidue, endResidue);
    }

    private List<Grade> getChildrens(Grade root, List<Grade> all) {
        List<Grade> children = all.stream().filter(m ->
                Objects.equals(m.getTeamPid(), root.getTeamId())).map(
                (m) -> {
                    m.setChildren(getChildrens(m, all));
                    return m;
                }
        ).collect(Collectors.toList());
        return children;
    }

    @Override
    public StudentGrade getLastOne(Integer yearPart, Integer quarterNum, Long subjectsId, Long studentId, Integer lessonType) {
        return studentGradeMapper.getLastOne(yearPart, quarterNum, subjectsId, studentId, lessonType);
    }

    /**
     * 获取本学期使用课时
     *
     * @param yearPart
     * @param quarterNum
     * @param subjectsId
     * @param schoolId
     * @param studentId
     * @return
     */
    public Long getStudentUseCourseCount(Integer yearPart, Integer quarterNum, Long schoolId, Long subjectsId, Long studentId, Integer lessonType) {
        return studentGradeMapper.getStudentUseCourseCount(yearPart, quarterNum, subjectsId, studentId, lessonType);
    }

    @Override
    public StudentGrade getLastForMaxId(Integer yearPart, Integer quarterNum, Long subjectsId, Long studentId, Integer lessonType) {
        return studentGradeMapper.getLastForMaxId(yearPart, quarterNum, subjectsId, studentId, lessonType);
    }

    @Override
    public List<StudentGrade> adjustGradeList(Integer yearPart, Integer quarterNum, Integer type, String schoolId, String yearClassId, String classTypeId, String subjectsId, String name, String teamId, String classify, String trackType, Integer isDetails) {

        List<StudentGrade> studentGradeList = new ArrayList<>();

        if (type == 5) {
            if (StringUtils.isNotBlank(teamId)) {
                String teamIdItem = trackMarketMapper.getTrackMarketChIdAll(Long.parseLong(teamId));
                if (StringUtils.isNotBlank(teamIdItem)) {
                    teamId = teamIdItem;
                }
            }
            studentGradeList = studentGradeMapper.adjustGradeTeamList(yearPart, quarterNum, schoolId, yearClassId, type, subjectsId, classTypeId, isDetails, teamId, classify, trackType);

        } else {
            studentGradeList = studentGradeMapper.adjustGradeList(yearPart, quarterNum, schoolId, yearClassId, type, subjectsId, classTypeId, name);

            if (type == 6 && StringUtils.isBlank(schoolId)) {
                List<StudentGrade> collectList = new ArrayList<>();

                QueryWrapper queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("year_part", yearPart);
                queryWrapper.eq("quarter_num", quarterNum);
                queryWrapper.eq("pid", 0);
                List<SchoolQuarter> schoolQuarterList = iSchoolQuarterService.list(queryWrapper);

                for (SchoolQuarter schoolQuarter : schoolQuarterList) {
                    StudentGrade studentGrade = new StudentGrade();
                    studentGrade.setSchoolId(schoolQuarter.getSchoolId());
                    studentGrade.setSchoolName(schoolQuarter.getSchoolName());
                    studentGrade.setSchoolPid(schoolQuarter.getPid());
                    studentGrade.setYetAdjustCount(0);
                    studentGrade.setNotAdjustCount(0);

                    collectList.add(studentGrade);
                }

                for (StudentGrade arrivalRate : collectList) {
                    List<StudentGrade> childRates = new ArrayList<>();
                    for (StudentGrade arrivalRateChild : studentGradeList) {
                        if (arrivalRate.getSchoolId().equals(arrivalRateChild.getSchoolId()) || arrivalRate.getSchoolId().equals(arrivalRateChild.getSchoolPid())) {
                            childRates.add(arrivalRateChild);
                            if (arrivalRateChild.getYetAdjustCount() != null) {
                                arrivalRate.setYetAdjustCount(arrivalRate.getYetAdjustCount() + arrivalRateChild.getYetAdjustCount());
                            }
                            if (arrivalRateChild.getNotAdjustCount() != null) {
                                arrivalRate.setNotAdjustCount(arrivalRate.getNotAdjustCount() + arrivalRateChild.getNotAdjustCount());
                            }
                        }
                    }
                    arrivalRate.setChildRateList(childRates);
                }
                studentGradeList = collectList;
            }
        }

        return studentGradeList;
    }

    @Override
    public IPage<StudentGrade> adjustGradeDetails(IPage<?> page, Integer yearPart, Integer quarterNum, String schoolId, String yearClassId, Integer type, String classTypeId, String gradeId, String teamId, String classify, String trackType, Integer detailType, String subjectsId, String teacherId) {
        IPage<StudentGrade> studentGradePage = new Page<>();

        if (type == 5) {

            studentGradePage = studentGradeMapper.adjustGradeTeamDetails(page, yearPart, quarterNum, schoolId, detailType, subjectsId, yearClassId, classTypeId, teacherId, gradeId, teamId, classify, trackType);
        } else {

            studentGradePage = studentGradeMapper.adjustGradeDetails(page, yearPart, quarterNum, detailType, schoolId, subjectsId, yearClassId, classTypeId, teacherId, gradeId);
        }

        return studentGradePage;
    }


}
